from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time

def simple_baidu_search():
    print("=== 简单百度搜索示例 ===")
    
    # 设置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--window-size=1920,1080')
    
    driver = None
    try:
        # 使用webdriver-manager自动管理ChromeDriver
        print("正在自动下载和配置ChromeDriver...")
        service = Service(ChromeDriverManager().install())
        print("ChromeDriver准备就绪")
        
        # 启动浏览器
        print("正在启动浏览器...")
        driver = webdriver.Chrome(service=service, options=chrome_options)
        driver.implicitly_wait(10)  # 设置隐式等待为10秒
        print("浏览器已启动")
        
        # 访问百度首页
        print("正在访问百度首页...")
        driver.get("https://www.baidu.com")
        print("已访问百度首页")
        
        # 等待页面加载
        time.sleep(5)
        
        # 查找搜索框
        print("正在查找搜索框...")
        search_box = driver.find_element(By.ID, "kw")
        print("搜索框已找到")
        
        # 使用JavaScript确保元素可交互
        driver.execute_script("arguments[0].scrollIntoView();", search_box)
        time.sleep(1)
        
        # 输入搜索关键词
        print("正在输入搜索关键词...")
        driver.execute_script("arguments[0].value = '莫烦Python';", search_box)
        print("已输入搜索关键词")
        
        # 触发输入事件
        driver.execute_script("arguments[0].dispatchEvent(new Event('input'));", search_box)
        time.sleep(1)
        
        # 查找搜索按钮并点击
        print("正在查找搜索按钮...")
        search_button = driver.find_element(By.ID, "su")
        print("搜索按钮已找到")
        
        # 使用JavaScript点击搜索按钮
        print("正在点击搜索按钮...")
        driver.execute_script("arguments[0].click();", search_button)
        print("已点击搜索按钮")
        
        # 等待搜索结果加载
        print("正在等待搜索结果加载...")
        time.sleep(5)
        print("搜索结果已加载")
        
        # 获取当前URL
        current_url = driver.current_url
        print("搜索结果页面URL:", current_url)
        
        # 检查是否出现验证码
        if "wappass.baidu.com" in current_url:
            print("被重定向到验证码页面")
        else:
            print("成功获取搜索结果页面")
            # 获取搜索结果
            results = driver.find_elements(By.CSS_SELECTOR, "h3 a")
            print(f"找到 {len(results)} 个搜索结果:")
            
            for i, result in enumerate(results[:5]):  # 只显示前5个结果
                title = result.text
                link = result.get_attribute("href")
                print(f"{i+1}. {title}")
                print(f"   链接: {link}")
        
    except Exception as e:
        print(f"发生错误: {e}")
        import traceback
        traceback.print_exc()
    finally:
        if driver:
            try:
                driver.quit()
                print("浏览器已关闭")
            except:
                print("关闭浏览器时出错")

if __name__ == "__main__":
    simple_baidu_search()